package cn.source.web.controller.accountWeb;
import cn.source.system.account.dto.*;
import cn.source.system.account.exception.ApplicationException;
import cn.source.system.account.exception.ErrorCode;
import cn.source.system.account.service.AccountService;
import cn.source.system.account.service.RoleService;
import cn.source.system.common.domain.vo.JsonResult;
import cn.source.system.config.security.CurrUserDetails;
import com.taobao.api.ApiException;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
 * <p>
 * AccountController.java此类用于账号管理
 * </p>
 * <p>
 * @author:YXZhou
 * </p>
 * <p>
 * @remark:
 * </p>
 */
@Api(tags = {"账号管理API"})
@Slf4j
@RestController
@RequestMapping
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private RoleService roleService;
    /**
     * 获取账号列表
     * @param accountQueryParams
     * @return
     * @author YXZhou
     */
    @ApiOperation(value = "账号查询")
    @ApiResponses({@ApiResponse(code = 0, message = "查询成功")})
    @GetMapping(value = "/account/list/page")
    public JsonResult pageAccountByConditions(AccountQueryParams accountQueryParams) {
        CurrUserDetails userDetails = (CurrUserDetails)
            SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        accountQueryParams.setTenantId(userDetails.getTenantId());
        Map<String, Object> map = accountService.pageAccountByConditions(accountQueryParams);
        List<AccountDTO> list = (List<AccountDTO>) map.get("list");
        return JsonResult.ok(list);
    }
    /**
     * 检查用户名是否存在
     * @param username
     * @return
     * @author:YXZhou
     */
    @GetMapping(value = "/account/userName/exist")
    public boolean validUserNameExist(String username) {
        Map<String, Object> map = accountService.validUserNameExist(username);
        boolean exist = (boolean) map.get("exist");
        return exist;
    }
    /**
     * 添加用户
     * @param account
     * @return
     * @author:YXZhou
     */
    @ApiOperation(value = "账号添加")
    @ApiResponses({@ApiResponse(code = 0, message = "添加成功")})
    @PostMapping(value = "/account")
    public JsonResult add(AccountDTO account) {
        CurrUserDetails userDetails = (CurrUserDetails)
            SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        accountService.createAccount(account, userDetails.getTenantId());
        return JsonResult.ok();
    }
    /**
     * 获取用户信息
     * @param username
     * @return
     * @author:YXZhou
     */
    @GetMapping(value = "/account/{username}")
    public JsonResult getAccount(@PathVariable("username") String username) {
        AccountDTO accountDTO = accountService.getAccount(username);
        return JsonResult.ok(accountDTO);
    }
    /**
     * 修改账号（修改手机号）
     *
     * @param modifyMobileParams
     * @return
     * @author:YXZhou
     */
    @PutMapping(value = "/account/mobile")
    public JsonResult updateMobile(ModifyMobileParams modifyMobileParams) {
        accountService.modifyAccountMobile(modifyMobileParams.getUsername(), modifyMobileParams.getMobile());
        return JsonResult.ok();
    }
    /**
     * 修改密码
     *
     * @param modifyPasswordParams
     * @return
     * @author:YXZhou
     */
    @PutMapping(value = "/account/password")
    public Map<String, Object> updatePwd(@RequestBody ModifyPasswordParams modifyPasswordParams) {
        CurrUserDetails userDetails = (CurrUserDetails) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();
        modifyPasswordParams.setUsername(userDetails.getUsername());
        Map<String, Object> returnMap = accountService.modifyAccountPassword(modifyPasswordParams);
        return returnMap;
    }
    /**
     * 删除用户
     * @return
     * @author:YXZhou
     */
    @DeleteMapping(value = "/account/{userName}")
    public JsonResult delete(@PathVariable("userName") String userName) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof CurrUserDetails) {
            CurrUserDetails userDetails = (CurrUserDetails) principal;
            accountService.delete(userName, userDetails.getTenantId());
            return JsonResult.ok();
        } else {
            throw new ApplicationException(ErrorCode.E_100110);
        }
    }
    /**
     * 获取已绑定角色
     *
     * @return
     * @author:YXZhou
     */
    @ApiOperation("获取某账号已绑定的角色")
    @ApiImplicitParam(name = "userName", value = "账号名", required = true, dataType = "String", paramType = "path")
    @GetMapping(value = "/account/role")
    public JsonResult getAccountRole(String username) {
        CurrUserDetails userDetails = (CurrUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> roleCodeList = accountService.getAccountRole(username, userDetails.getTenantId());
        return JsonResult.ok(roleCodeList);
    }
    /**
     * 账号绑定角色
     *
     * @param username
     * @param role
     * @return
     * @author:YXZhou
     */
    @ApiOperation("绑定角色")
    @ApiImplicitParams({@ApiImplicitParam(name = "userName", value = "账号", dataType = "String", paramType = "path"),
        @ApiImplicitParam(name = "role", value = "角色，可以多个,String数组", required = true, dataType = "String[]", paramType = "query"),})
    @PostMapping(value = "/account/role/actions/bind")
    public JsonResult bindRole(String username, String[] role) {
        CurrUserDetails userDetails = (CurrUserDetails) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();
        accountService.bindRole(username, userDetails.getTenantId(), role);
        return JsonResult.ok();
    }
    /**
     * 查询角色
     *
     * @return
     * @author:YXZhou
     */
    @ApiOperation("查询角色")
    @GetMapping(value = "/account/queryRole")
    @ResponseBody
    public JsonResult queryRole() {
        CurrUserDetails userDetails = (CurrUserDetails) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();
        List<TenantRoleDTO> returnMap = roleService.queryTenantRole(userDetails.getTenantId());
        return JsonResult.ok(returnMap);
    }
    /**
     * 查询已有权限
     * @return
     * @author YXZhou
     */
    @ApiOperation("查询某一角色下已有权限")
    @ApiImplicitParam(name = "code", value = "角色编码", required = true, dataType = "String", paramType = "path")
    @GetMapping(value = "/account/queryBindPrivilege/{code}")
    public Map<String, Object> queryBindPrivilege(@PathVariable("code") String code) {
        Map<String, Object> returnMap = roleService.queryBindPrivilege(code);
        return returnMap;
    }
    /**
     * 绑定权限
     * @param code
     * @param privileges
     * @return
     */
    @ApiOperation("为某一角色绑定权限")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "code", value = "角色编码", required = true, dataType = "String", paramType = "path"),
        @ApiImplicitParam(name = "privileges", value = "权限  List<String>", required = true, dataType = "List<String>", paramType = "body"),})
    @PostMapping(value = "/account/bindPrivilege/{code}")
    public Map<String, Object> bindPrivilege(@PathVariable("code") String code, String[] privileges) {
        List<String> pri = Arrays.asList(privileges);
        Map<String, Object> returnMap = roleService.bindPrivilege(code, pri);
        return returnMap;
    }
    /**
     * 查询登录所用租户的所有权限
     * @return
     * @author YXZhou
     */
    @ApiOperation("查询登录租户的所有权限,权限树")
    @GetMapping(value = "/account/role/privilegeTree")
    public Map<String, Object> queryPrivilegeTree() throws ApiException {
        CurrUserDetails userDetails = (CurrUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Map<String, Object> returnMap = roleService.queryPrivilegeTree(userDetails.getTenantType());
        return returnMap;
    }
    /**
     * 添加角色
     * @param role
     * @return
     * @author YXZhou
     */
    @PostMapping(value = "/account/role")
    public JsonResult add(TenantRoleDTO role) {
        CurrUserDetails userDetails = (CurrUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        roleService.createTenantRole(userDetails.getTenantId(), role);
        return JsonResult.ok();
    }
    /**
     * 修改角色
     * @param role
     * @return
     * @author YXZhou
     */
    @PutMapping(value = "/account/role")
    public JsonResult update(TenantRoleDTO role) {
        CurrUserDetails userDetails = (CurrUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        roleService.modifyTenantRole(userDetails.getTenantId(), role);
        return JsonResult.ok();
    }
    /**
     * 删除角色
     * @param code
     * @return
     * @author 孔得峰
     * @date 2018年8月15日 上午10:14:44
     */
    @DeleteMapping(value = "/account/role/{code}")
    public JsonResult deleteRole(@PathVariable("code") String code) {
        CurrUserDetails userDetails = (CurrUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        roleService.removeTenantRole(userDetails.getTenantId(), code);
        return JsonResult.ok();
    }
    /**
     * 密码重置
     * @param modifyPasswordParams
     * @return
     */
    @PostMapping("/account/resetPwd")
    public Map<String, Object> resetPwd(ModifyPasswordParams modifyPasswordParams) {
        Map<String, Object> returnMap = accountService.resetAccountPassword(modifyPasswordParams);
        return returnMap;
    }
}
